<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [huoyuan].
 */
namespace service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\Exception;

/**
 * 基于guzzle异步请求框架封装HTTP请求服务
 * Class HttpService.
 */
class HttpService
{
    /**
     * 以get模拟网络请求
     *
     * @param string $url     HTTP请求URL地址
     * @param array  $query   GET请求参数
     * @param array  $options CURL参数
     *
     * @throws GuzzleException
     * @throws Exception
     *
     * @return bool|string
     */
    public static function get($url, $query = [], $options = [])
    {
        $options['query'] = $query;

        return HttpService::request('get', $url, $options);
    }

    /**
     * 以get模拟网络请求
     *
     * @param string $url     HTTP请求URL地址
     * @param array  $data    POST请求数据
     * @param array  $options CURL参数
     *
     * @throws GuzzleException
     * @throws Exception
     *
     * @return bool|string
     */
    public static function post($url, $data = [], $options = [])
    {
        //默认使用json作为传输数据
        if (is_array($data)) {
            $options['json'] = $data;
        } else {
            $options['form_params'] = $data;
        }

        return HttpService::request('post', $url, $options);
    }

    /**
     * Guzzle模拟网络请求
     *
     * @param string $method  请求方法
     * @param string $url     请求方法
     * @param array  $options 请求参数[header,json,ssl_cer,ssl_key]
     *
     * @throws GuzzleException
     * @throws Exception
     *
     * @return bool|string
     */
    public static function request($method, $url, $options = [])
    {
        //关闭error异常抛出的问题
        $options['http_errors'] = false;

        //如果没设置超时时间, 默认设置30秒
        if (!isset($options['timeout'])) {
            $options['timeout'] = 30.0;
        }

        try {
            $httpClient = new Client();
            $response = $httpClient->request($method, $url, $options);

            if (200 !== intval($response->getStatusCode())) {
                throw new \Exception('接口报错:' . $response->getStatusCode());
            }

            return $response->getBody()->getContents();
        } catch (GuzzleException $e) {
            throw $e;
        }
    }
}
